package org.linlinjava.litemall.admin.service.order_manage;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.hibernate.validator.constraints.SafeHtml;
import org.linlinjava.litemall.admin.form.*;
import org.linlinjava.litemall.admin.vo.order_manage.*;
import org.linlinjava.litemall.core.config.BizException;
import org.linlinjava.litemall.core.util.InventoryUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.order_manage.BackendGoodsMapper;
import org.linlinjava.litemall.db.dao.order_manage.BackendStoreMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.jsonfield.GoodsTagInfo;
import org.linlinjava.litemall.db.jsonfield.LitemallGoodsProductSpecification;
import org.linlinjava.litemall.db.service.AgedmallCloudHouseService;
import org.linlinjava.litemall.db.service.AgedmallGoodsDeductionConfService;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.order_manage.*;
import org.linlinjava.litemall.db.vo.store.ExpressModelForm;
import org.linlinjava.litemall.db.vo.store.PickUpModelForm;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class AgedmallCommodityService {

    @Resource
    private LitemallGoodsMapper litemallGoodsMapper;
    @Resource
    private BackendGoodsMapper backendGoodsMapper;
    @Resource
    private AgedmallBusiAdminMapper agedmallBusiAdminMapper;
    @Resource
    private AgedmallGoodsSpecificationInfoMapper agedmallGoodsSpecificationInfoMapper;
    @Resource
    private LitemallGoodsSpecificationMapper litemallGoodsSpecificationMapper;
    @Resource
    private LitemallGoodsProductMapper litemallGoodsProductMapper;
    @Resource
    private AgedmallGoodsPartsMapper agedmallGoodsPartsMapper;
    @Resource
    private AgedmallGoodsServiceMapper agedmallGoodsServiceMapper;
    @Resource
    private BackendStoreMapper backendStoreMapper;
    @Resource
    private AgedmallGoodsDeductionConfMapper agedmallGoodsDeductionConfMapper;
    @Resource
    private AgedmallStoreGoodsMapper agedmallStoreGoodsMapper;
    @Resource
    private AgedmallStoreGoodsProductMapper agedmallStoreGoodsProductMapper;
    @Resource
    private AgedmallExplainMapper agedmallExplainMapper;
    @Resource
    private AgedmallStoreMapper agedmallStoreMapper;
    @Resource
    private AgedmallGoodsOnlineServiceMapper agedmallGoodsOnlineServiceMapper;
    @Resource
    private AgedmallClassifyMapper agedmallClassifyMapper;
    @Resource
    private AgedmallGoodsEquMapper agedmallGoodsEquMapper;
    @Resource
    private AgedmallOnlineServiceProductMapper agedmallOnlineServiceProductMapper;
    @Resource
    private AgedmallCustomGoodsMapper agedmallCustomGoodsMapper;
    @Resource
    private InventoryUtil inventoryUtil;
    @Resource
    private AgedmallTagsMapper agedmallTagsMapper;
    @Resource
    private AgedmallCloudHouseService agedmallCloudHouseService;

    @Resource
    private AgedmallCloudHouseMapper agedmallCloudHouseMapper;

    @Resource
    private AgedmallCollectionPointsMapper agedmallCollectionPointsMapper;

    public Object listCommodity(Integer busiId, String commodityName, Integer commdityType, Integer commditySubType, Integer commdityState,
                                String goodsType, Integer hasSku, Integer storeId, Integer isRelate, Integer page, Integer limit){
        // 有分类按分类排序规则排序
        String sort = "g.add_time", desc = "desc";
        if (null != commdityType) {
            AgedmallClassify classify = agedmallClassifyMapper.selectByPrimaryKey(commdityType);
            if (null != classify && null != classify.getShowSort()) {
                if (0 == classify.getShowSort()) {
                    sort = "g.add_time";
                    desc = null;
                }
                if (1 == classify.getShowSort()) {
                    sort = "g.add_time";
                    desc = "desc";
                }
                if (2 == classify.getShowSort()) {
                    sort = "gsi.sale_count";
                    desc = "desc";
                }
            }
        }
        PageHelper.startPage(page, limit);
        List<BackendGoodsListVo> list = backendGoodsMapper.goodsList(busiId, commodityName, commdityType, commditySubType, commdityState, goodsType, storeId, isRelate, sort, desc);
        // 是否需要sku
        if (null != hasSku && hasSku == 1) {
            for (BackendGoodsListVo goods : list) {
                AgedmallGoodsSpecificationInfoExample infoExample = new AgedmallGoodsSpecificationInfoExample();
                infoExample.createCriteria().andDeletedEqualTo(false)
                        .andGoodsIdEqualTo(goods.getGoodsId())
                        .andTypeEqualTo(GoodsSpecificationConstant.TYPE_SPEC);
                List<AgedmallGoodsSpecificationInfo> infoList = agedmallGoodsSpecificationInfoMapper.selectByExample(infoExample);
                List<BackendGoodsSkuListVo> goodsSkuList = infoList.stream()
                        .map(p -> {
                            BackendGoodsSkuListVo sku = new BackendGoodsSkuListVo();
                            sku.setSkuId(p.getId());
                            sku.setName(p.getSpecName());
                            LitemallGoodsSpecificationExample specExample = new LitemallGoodsSpecificationExample();
                            specExample.createCriteria().andDeletedEqualTo(false)
                                    .andParentIdEqualTo(p.getId());
                            List<LitemallGoodsSpecification> specificationList = litemallGoodsSpecificationMapper.selectByExample(specExample);
                            List<BackendGoodsSkuSpecListVo> specList = specificationList.stream()
                                    .map(q -> {
                                        BackendGoodsSkuSpecListVo spec = new BackendGoodsSkuSpecListVo();
                                        spec.setId(q.getId());
                                        spec.setName(q.getValue());
                                        return spec;
                                    }).collect(Collectors.toList());
                            sku.setSpecList(specList);
                            return sku;
                        }).collect(Collectors.toList());
                goods.setSkuList(goodsSkuList);
            }
        }
        return ResponseUtil.okList(list);
    }

    public Object categoryList(Integer busiId) {
         List<GoodsCategoryVo> list = backendGoodsMapper.categoryList(busiId);
        for (GoodsCategoryVo goodsCategoryVo : list) {
            goodsCategoryVo.setChildren(backendGoodsMapper.subCategoryList(busiId, goodsCategoryVo.getValue()));
        }
        return ResponseUtil.ok(list);
    }

    @Transactional
    public Object addCommodity(Integer busiId, CommodityAddForm commodityAddForm) {
        // 判断配件商品 是否重复
        List<CommodityAddExtralForm> addExtralForm = commodityAddForm.getExtral();
        if (CollectionUtils.isNotEmpty(addExtralForm)) {
            List<Integer> goodsIdList = new ArrayList<>();
            for (CommodityAddExtralForm commodityAddExtralForm : addExtralForm) {
                List<CommodityAddExtralListForm> addExtralListForms = commodityAddExtralForm.getValues();
                if (CollectionUtils.isNotEmpty(addExtralListForms)) {
                    List<Integer> goodsIds = addExtralListForms.stream().map(p -> p.getCommodityid()).collect(Collectors.toList());
                    goodsIdList.addAll(goodsIds);
                }
            }
            long count = goodsIdList.stream().distinct().count();
            if (count != goodsIdList.size()) {
                throw new BizException("配件商品不能重复");
            }
        }

        // 保存商品
        LitemallGoods goods = new LitemallGoods();
        goods.setLength(commodityAddForm.getLength());
        goods.setWidth(commodityAddForm.getWidth());
        goods.setHeight(commodityAddForm.getHeight());
        goods.setName(commodityAddForm.getCommodityName());
        goods.setNameTag(commodityAddForm.getCommodityNameTag());
        goods.setBrief(commodityAddForm.getCommodityBrief());
        goods.setGallery(commodityAddForm.getCommodityImage());
        goods.setPicUrl(null != commodityAddForm.getCommodityImage() ? commodityAddForm.getCommodityImage()[0] : null);
        goods.setVideo(commodityAddForm.getCommodityVideo());
        goods.setCategoryType(commodityAddForm.getCommodityClass());
        if (null != commodityAddForm.getCommodityLabel()) {
            List<GoodsTagInfo> tagInfos = new ArrayList<>();
            for (String tag : commodityAddForm.getCommodityLabel()) {
                AgedmallTags tags = agedmallTagsMapper.selectByPrimaryKey(Long.parseLong(tag));
                if (null != tags) {
                    GoodsTagInfo tagInfo = new GoodsTagInfo();
                    tagInfo.setTagId(Integer.parseInt(tag));
                    tagInfo.setTag(tags.getName());
                    tagInfo.setIsRed(tags.getProminent());
                    tagInfos.add(tagInfo);
                }
            }
            goods.setTags(JSON.toJSONString(tagInfos));
        }
        goods.setGoodsType(commodityAddForm.getCommodityType());
        goods.setCounterPrice(commodityAddForm.getCost());
        goods.setRetailPrice(commodityAddForm.getOrginalPrice());
        goods.setShareUrl(commodityAddForm.getShare());
        goods.setDeposit(commodityAddForm.getDeposit());
        goods.setUnit(commodityAddForm.getUnit());
        goods.setWeight(commodityAddForm.getWeight());
        goods.setDetail(commodityAddForm.getCommodityDetail());
        goods.setVipPriceFlag(commodityAddForm.getvIPPrice());

        if (null == commodityAddForm.getCommodityId()) {
            goods.setBusId(busiId);
            goods.setGoodsSn(getGoodsSn());
            goods.setAddTime(LocalDateTime.now());
            goods.setDeleted(false);
            litemallGoodsMapper.insertSelective(goods);
        } else {
            goods.setUpdateTime(LocalDateTime.now());
            goods.setId(commodityAddForm.getCommodityId());
            litemallGoodsMapper.updateByPrimaryKeySelective(goods);
        }

        // 如果是更新 先删除
        if (null != commodityAddForm.getCommodityId()) {
//            // 删除规格类型表
//            AgedmallGoodsSpecificationInfoExample agedmallGoodsSpecificationInfoExample = new AgedmallGoodsSpecificationInfoExample();
//            agedmallGoodsSpecificationInfoExample.createCriteria().andDeletedEqualTo(false)
//                    .andGoodsIdEqualTo(goods.getId());
//            agedmallGoodsSpecificationInfoMapper.logicalDeleteByExample(agedmallGoodsSpecificationInfoExample);
//            // 删除规格表
//            LitemallGoodsSpecificationExample litemallGoodsSpecificationExample = new LitemallGoodsSpecificationExample();
//            litemallGoodsSpecificationExample.createCriteria().andDeletedEqualTo(false)
//                    .andGoodsIdEqualTo(goods.getId());
//            litemallGoodsSpecificationMapper.logicalDeleteByExample(litemallGoodsSpecificationExample);
//            // 删除规格商品表
//            LitemallGoodsProductExample litemallGoodsProductExample = new LitemallGoodsProductExample();
//            litemallGoodsProductExample.createCriteria().andDeletedEqualTo(false)
//                    .andGoodsIdEqualTo(goods.getId());
//            litemallGoodsProductMapper.logicalDeleteByExample(litemallGoodsProductExample);
//            // 删除配件表
//            AgedmallGoodsPartsExample agedmallGoodsPartsExample = new AgedmallGoodsPartsExample();
//            agedmallGoodsPartsExample.createCriteria().andDeletedEqualTo(false)
//                    .andGoodsIdEqualTo(goods.getId());
//            agedmallGoodsPartsMapper.logicalDeleteByExample(agedmallGoodsPartsExample);
//            // 删除服务表
//            AgedmallGoodsServiceExample agedmallGoodsServiceExample = new AgedmallGoodsServiceExample();
//            agedmallGoodsServiceExample.createCriteria().andDeletedEqualTo(false)
//                    .andGoodsIdEqualTo(goods.getId());
//            agedmallGoodsServiceMapper.logicalDeleteByExample(agedmallGoodsServiceExample);
//            // 删除在线服务表
//            AgedmallGoodsOnlineServiceExample agedmallGoodsOnlineServiceExample = new AgedmallGoodsOnlineServiceExample();
//            agedmallGoodsOnlineServiceExample.createCriteria().andDeletedEqualTo(false)
//                    .andGoodsIdEqualTo(goods.getId());
//            agedmallGoodsOnlineServiceMapper.logicalDeleteByExample(agedmallGoodsOnlineServiceExample);
            // 删除抵扣金配置
            AgedmallCustomGoodsExample agedmallCustomGoodsExample = new AgedmallCustomGoodsExample();
            agedmallCustomGoodsExample.createCriteria().andDeletedEqualTo(false)
                    .andBusIdEqualTo(busiId.longValue())
                    .andGoodsIdEqualTo(goods.getId());
            agedmallCustomGoodsMapper.logicalDeleteByExample(agedmallCustomGoodsExample);
            // 删除配件表
            AgedmallGoodsPartsExample agedmallGoodsPartsExample = new AgedmallGoodsPartsExample();
            agedmallGoodsPartsExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdEqualTo(goods.getId());
            agedmallGoodsPartsMapper.logicalDeleteByExample(agedmallGoodsPartsExample);
            // 删除在线服务表
            AgedmallGoodsOnlineServiceExample agedmallGoodsOnlineServiceExample = new AgedmallGoodsOnlineServiceExample();
            agedmallGoodsOnlineServiceExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdEqualTo(goods.getId());
            agedmallGoodsOnlineServiceMapper.logicalDeleteByExample(agedmallGoodsOnlineServiceExample);

        }

        // 保存抵扣金配置
        if (commodityAddForm.getRadio() == 1) {
            AgedmallCustomGoods agedmallCustomGoods = new AgedmallCustomGoods();
            agedmallCustomGoods.setBusId(busiId.longValue());
            agedmallCustomGoods.setGoodsId(goods.getId());
            if (null != commodityAddForm.getFix()) {
                agedmallCustomGoods.setConsumptionType(1);
                agedmallCustomGoods.setConsumptionPrice(commodityAddForm.getFix());
            } else {
                agedmallCustomGoods.setConsumptionType(0);
                agedmallCustomGoods.setConsumptionPrice(commodityAddForm.getPercent());
            }
            agedmallCustomGoods.setAddTime(LocalDateTime.now());
            agedmallCustomGoods.setDeleted(false);
            agedmallCustomGoodsMapper.insertSelective(agedmallCustomGoods);
        }
        // 保存规格
        List<CommodityAddRegualrForm> regualr = commodityAddForm.getRegualr();
        if (CollectionUtils.isNotEmpty(regualr)) {
            // 已保存的规格和其id
            Map<String, Integer> savedRegMap = new HashMap<>();
            for (CommodityAddRegualrForm commodityAddRegualrForm : regualr) {
                if (null != commodityAddRegualrForm.getProductId()) {
                    LitemallGoodsProduct product = litemallGoodsProductMapper.selectByPrimaryKey(commodityAddRegualrForm.getProductId());
                    if (null != product) {
                        product.setPrice(commodityAddRegualrForm.getCost());
                        product.setOriginalPrice(commodityAddRegualrForm.getOrginalPrice());
                        product.setDeposit(commodityAddRegualrForm.getDeposit());
                        product.setUrl(commodityAddRegualrForm.getPicture());
                        product.setWeight(commodityAddRegualrForm.getWeight());
                        product.setUpdateTime(LocalDateTime.now());
                        litemallGoodsProductMapper.updateByPrimaryKey(product);
                    }
                } else {
                    List<CommodityAddRegualrListForm> regualrs = commodityAddRegualrForm.getRegualrs();
                    // 规格组合
                    List<LitemallGoodsProductSpecification> specList = new ArrayList<>();
                    for (CommodityAddRegualrListForm listForm : regualrs) {
                        // name为规格类型，value为具体规格，没保存过进行保存
                        if (!savedRegMap.containsKey(listForm.getName())) {
                            AgedmallGoodsSpecificationInfo specificationInfo = new AgedmallGoodsSpecificationInfo();
                            specificationInfo.setGoodsId(goods.getId());
                            specificationInfo.setSpecName(listForm.getName());
                            specificationInfo.setType(GoodsSpecificationConstant.TYPE_SPEC);
                            specificationInfo.setAddTime(LocalDateTime.now());
                            specificationInfo.setDeleted(false);
                            agedmallGoodsSpecificationInfoMapper.insertSelective(specificationInfo);
                            savedRegMap.put(listForm.getName(), specificationInfo.getId());
                        }
                        if (!savedRegMap.containsKey(listForm.getName() + "@#$" + listForm.getValue())) {
                            LitemallGoodsSpecification specification = new LitemallGoodsSpecification();
                            specification.setGoodsId(goods.getId());
                            specification.setSpecification(listForm.getName());
                            specification.setValue(listForm.getValue());
                            specification.setParentId(savedRegMap.get(listForm.getName()));
                            specification.setAddTime(LocalDateTime.now());
                            specification.setDeleted(false);
                            litemallGoodsSpecificationMapper.insertSelective(specification);
                            savedRegMap.put(listForm.getName() + "@#$" + listForm.getValue(), specification.getId());
                        }
                        LitemallGoodsProductSpecification spec = new LitemallGoodsProductSpecification();
                        spec.setId(savedRegMap.get(listForm.getName() + "@#$" + listForm.getValue()));
                        spec.setName(listForm.getValue());
                        spec.setInfoId(savedRegMap.get(listForm.getName()));
                        spec.setInfoName(listForm.getName());
                        specList.add(spec);
                    }
                    // 保存规格商品
                    LitemallGoodsProduct product = new LitemallGoodsProduct();
                    product.setGoodsId(goods.getId());
                    product.setSpecifications(JSON.toJSONString(specList));
                    product.setPrice(commodityAddRegualrForm.getCost());
                    product.setOriginalPrice(commodityAddRegualrForm.getOrginalPrice());
                    product.setDeposit(commodityAddRegualrForm.getDeposit());
                    product.setUrl(commodityAddRegualrForm.getPicture());
                    product.setWeight(commodityAddRegualrForm.getWeight());
                    product.setVipJson(commodityAddRegualrForm.getVipJson());
                    product.setWidth(commodityAddRegualrForm.getWidth());
                    product.setHeight(commodityAddRegualrForm.getHeight());
                    product.setLength(commodityAddRegualrForm.getLength());

                    product.setType(GoodsProductConstant.TYPE_GOODS);
                    product.setAddTime(LocalDateTime.now());
                    product.setDeleted(false);
                    litemallGoodsProductMapper.insertSelective(product);
                }
            }
        }
        // 保存附加规格
        List<CommodityAddExtralForm> extral = commodityAddForm.getExtral();
        if (CollectionUtils.isNotEmpty(extral)) {
            for (CommodityAddExtralForm commodityAddExtralForm : extral) {
                // 保存规格类型
                AgedmallGoodsSpecificationInfo specificationInfo = new AgedmallGoodsSpecificationInfo();
                specificationInfo.setGoodsId(goods.getId());
                specificationInfo.setSpecName(commodityAddExtralForm.getName());
                specificationInfo.setType(commodityAddExtralForm.getType());
                specificationInfo.setDesc(commodityAddExtralForm.getDesc());
                specificationInfo.setMinSelCount(commodityAddExtralForm.getMustSelect());
                specificationInfo.setMultiSelFlg(commodityAddExtralForm.getMultiSelFlg() == 1);
                if (null != commodityAddExtralForm.getSpecInfoId()) {
                    specificationInfo.setId(commodityAddExtralForm.getSpecInfoId());
                    specificationInfo.setUpdateTime(LocalDateTime.now());
                    agedmallGoodsSpecificationInfoMapper.updateByPrimaryKeySelective(specificationInfo);
                } else {
                    specificationInfo.setAddTime(LocalDateTime.now());
                    specificationInfo.setDeleted(false);
                    agedmallGoodsSpecificationInfoMapper.insertSelective(specificationInfo);
                }


                for (CommodityAddExtralListForm listForm : commodityAddExtralForm.getValues()) {
                    // 保存规格
                    LitemallGoodsSpecification specification = new LitemallGoodsSpecification();
                    specification.setGoodsId(goods.getId());
                    specification.setSpecification(specificationInfo.getSpecName());
                    specification.setValue(listForm.getValue());
                    specification.setParentId(specificationInfo.getId());
                    if (null != listForm.getSpecId()) {
                        specification.setId(listForm.getSpecId());
                        specification.setUpdateTime(LocalDateTime.now());
                        litemallGoodsSpecificationMapper.updateByPrimaryKeySelective(specification);
                    } else {
                        specification.setAddTime(LocalDateTime.now());
                        specification.setDeleted(false);
                        litemallGoodsSpecificationMapper.insertSelective(specification);
                    }

                    // 配件
                    if (GoodsSpecificationConstant.TYPE_CUSTOM.equals(commodityAddExtralForm.getType())){
                        // 保存配件表
                        AgedmallGoodsParts parts = new AgedmallGoodsParts();
                        parts.setGoodsId(goods.getId());
                        parts.setSpecId(specification.getId());
                        parts.setCustomizedGoodsId(listForm.getCommodityid());
                        parts.setPayOrder(listForm.getPayOrder());
                        parts.setAddTime(LocalDateTime.now());
                        parts.setDeleted(false);
                        agedmallGoodsPartsMapper.insertSelective(parts);
                        // 在线服务
                    }else if (GoodsSpecificationConstant.TYPE_ONLINE.equals(commodityAddExtralForm.getType())){
                        // 保存在线服务表
                        AgedmallGoodsOnlineService onlineService = new AgedmallGoodsOnlineService();
                        onlineService.setGoodsId(goods.getId());
                        onlineService.setSpecId(specification.getId());
                        onlineService.setOnlineSerivceProductId(listForm.getCommodityid());
                        onlineService.setPayOrder(listForm.getPayOrder());
                        onlineService.setAddTime(LocalDateTime.now());
                        onlineService.setDeleted(false);
                        agedmallGoodsOnlineServiceMapper.insertSelective(onlineService);
                    }
                    // 普通服务
//                    else if (GoodsSpecificationConstant.TYPE_EXTEND.equals(commodityAddExtralForm.getType())) {
//                        // 规格组合
//                        List<LitemallGoodsProductSpecification> specList = new ArrayList<>();
//                        LitemallGoodsProductSpecification spec = new LitemallGoodsProductSpecification();
//                        spec.setId(specification.getId());
//                        spec.setName(specification.getValue());
//                        spec.setInfoId(specificationInfo.getId());
//                        spec.setInfoName(specificationInfo.getSpecName());
//                        specList.add(spec);
//
//                        // 保存规格商品
//                        LitemallGoodsProduct product = new LitemallGoodsProduct();
//                        product.setGoodsId(goods.getId());
//                        product.setSpecifications(JSON.toJSONString(specList));
//                        String type = GoodsSpecificationConstant.TYPE_CUSTOM.equals(commodityAddExtralForm.getType()) ? GoodsProductConstant.TYPE_PARTS : GoodsProductConstant.TYPE_SERVICE;
//                        product.setType(type);
//                        product.setAddTime(LocalDateTime.now());
//                        product.setDeleted(false);
////                        product.setPrice(goodsProduct.getPrice());
////                        product.setOriginalPrice(goodsProduct.getOriginalPrice());
////                        product.setWeight(goodsProduct.getWeight());
//                        litemallGoodsProductMapper.insertSelective(product);
//
//                        // 保存服务表
//                        AgedmallGoodsService service = new AgedmallGoodsService();
//                        service.setGoodsId(goods.getId());
//                        service.setProductId(product.getId());
//                        service.setSpecId(specification.getId());
//                        service.setServiceName(specification.getValue());
//                        service.setAddTime(LocalDateTime.now());
//                        service.setDeleted(false);
//                        agedmallGoodsServiceMapper.insertSelective(service);
//                    }
                }
            }

        }
        return ResponseUtil.ok();
    }

    // 生成商品编号
    private String getGoodsSn() {
        return UUID.randomUUID().toString();
    }

    public Object commodityDetail(Integer goodsId) {
        CommodityDetailVo commodityDetailVo = new CommodityDetailVo();
        // 组装商品
        LitemallGoods goods = litemallGoodsMapper.selectByPrimaryKey(goodsId);
        if (null != goods) {
            commodityDetailVo.setCommodityId(goods.getId());
            commodityDetailVo.setCommodityName(goods.getName());
            commodityDetailVo.setCommodityNameTag(goods.getNameTag());
            commodityDetailVo.setCommodityBrief(goods.getBrief());
            commodityDetailVo.setCommodityImage(goods.getGallery());
            commodityDetailVo.setCommodityVideo(goods.getVideo());
            commodityDetailVo.setCommoditySubClass(goods.getCategoryType());
            AgedmallClassify agedmallClassify = agedmallClassifyMapper.selectByPrimaryKey(goods.getCategoryType());
            if (null != agedmallClassify) {
                commodityDetailVo.setCommodityClass(agedmallClassify.getPid());
            }
            List<GoodsTagInfo> tagInfos = JSON.parseArray(goods.getTags(), GoodsTagInfo.class);
            if (null != tagInfos) {
                String[] labels = tagInfos.stream().map(p -> p.getTagId()+"").toArray(String[]::new);
                commodityDetailVo.setCommodityLabel(labels);
            }
            commodityDetailVo.setCommodityType(goods.getGoodsType());
            commodityDetailVo.setCost(goods.getCounterPrice());
            commodityDetailVo.setOrginalPrice(goods.getRetailPrice());
            commodityDetailVo.setShare(goods.getShareUrl());
            commodityDetailVo.setWeight(goods.getWeight());
            commodityDetailVo.setLength(goods.getLength());
            commodityDetailVo.setWidth(goods.getWidth());
            commodityDetailVo.setHeight(goods.getHeight());
            commodityDetailVo.setLength(goods.getLength());
            commodityDetailVo.setDeposit(goods.getDeposit());
            commodityDetailVo.setUnit(goods.getUnit());
            commodityDetailVo.setvIPPrice(goods.getVipPriceFlag());
            commodityDetailVo.setCommodityDetail(goods.getDetail());
        }
        // 组装抵扣金
        AgedmallCustomGoodsExample agedmallCustomGoodsExample = new AgedmallCustomGoodsExample();
        agedmallCustomGoodsExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goods.getId());
        AgedmallCustomGoods customGoods = agedmallCustomGoodsMapper.selectOneByExample(agedmallCustomGoodsExample);
        if (null != customGoods) {
            commodityDetailVo.setRadio(1);
            if (1 == customGoods.getConsumptionType()) {
                commodityDetailVo.setFix(customGoods.getConsumptionPrice());
            } else {
                commodityDetailVo.setPercent(customGoods.getConsumptionPrice());
            }
        } else {
            commodityDetailVo.setRadio(0);
        }
        // 组装常规规格
        List<CommodityDetailRegualrNameForm> regualrList = new ArrayList<>();
        AgedmallGoodsSpecificationInfoExample agedmallGoodsSpecificationInfoExample = new AgedmallGoodsSpecificationInfoExample();
        agedmallGoodsSpecificationInfoExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goodsId)
                .andTypeEqualTo(GoodsSpecificationConstant.TYPE_SPEC);
        List<AgedmallGoodsSpecificationInfo> goodsSpecificationInfoList = agedmallGoodsSpecificationInfoMapper.selectByExample(agedmallGoodsSpecificationInfoExample);
        for (AgedmallGoodsSpecificationInfo specificationInfo : goodsSpecificationInfoList) {
            CommodityDetailRegualrNameForm commodityDetailRegualrNameForm = new CommodityDetailRegualrNameForm();
            commodityDetailRegualrNameForm.setSpecInfoId(specificationInfo.getId());
            commodityDetailRegualrNameForm.setName(specificationInfo.getSpecName());

            List<CommodityDetailRegualrValueForm> valueList = new ArrayList<>();
            LitemallGoodsSpecificationExample litemallGoodsSpecificationExample = new LitemallGoodsSpecificationExample();
            litemallGoodsSpecificationExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdEqualTo(goodsId)
                    .andParentIdEqualTo(specificationInfo.getId());
            List<LitemallGoodsSpecification> specificationList = litemallGoodsSpecificationMapper.selectByExample(litemallGoodsSpecificationExample);
            for (LitemallGoodsSpecification litemallGoodsSpecification : specificationList) {
                CommodityDetailRegualrValueForm commodityDetailRegualrValueForm = new CommodityDetailRegualrValueForm();
                commodityDetailRegualrValueForm.setSpecId(litemallGoodsSpecification.getId());
                commodityDetailRegualrValueForm.setValue(litemallGoodsSpecification.getValue());
                valueList.add(commodityDetailRegualrValueForm);
            }
            commodityDetailRegualrNameForm.setValueList(valueList);
            regualrList.add(commodityDetailRegualrNameForm);
        }
        commodityDetailVo.setRegualrList(regualrList);

        // 组装常规规格商品
        List<CommodityDetailRegualrForm> regualrCombo = new ArrayList<>();
        LitemallGoodsProductExample litemallGoodsProductExample = new LitemallGoodsProductExample();
        litemallGoodsProductExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goodsId)
                .andTypeEqualTo(GoodsProductConstant.TYPE_GOODS);
        List<LitemallGoodsProduct> litemallGoodsProductList = litemallGoodsProductMapper.selectByExample(litemallGoodsProductExample);
        for (LitemallGoodsProduct product : litemallGoodsProductList) {
            CommodityDetailRegualrForm commodityDetailRegualrForm = new CommodityDetailRegualrForm();
            commodityDetailRegualrForm.setProductId(product.getId());
            commodityDetailRegualrForm.setCost(product.getPrice());
            commodityDetailRegualrForm.setOrginalPrice(product.getOriginalPrice());
            commodityDetailRegualrForm.setDeposit(product.getDeposit());
            commodityDetailRegualrForm.setPicture(product.getUrl());
            commodityDetailRegualrForm.setWeight(product.getWeight());
            commodityDetailRegualrForm.setVipJson(product.getVipJson());
            commodityDetailRegualrForm.setWidth(product.getWidth());
            commodityDetailRegualrForm.setHeight(product.getHeight());
            commodityDetailRegualrForm.setLength(product.getLength());

            List<CommodityDetailRegualrListForm> regualrListForms = new ArrayList<>();
            List<LitemallGoodsProductSpecification> specList = JSON.parseArray(product.getSpecifications(), LitemallGoodsProductSpecification.class);
            for (LitemallGoodsProductSpecification specification : specList) {
                CommodityDetailRegualrListForm regualrListForm = new CommodityDetailRegualrListForm();
                regualrListForm.setSpecId(specification.getId());
                regualrListForm.setName(specification.getInfoName());
                regualrListForm.setValue(specification.getName());
                regualrListForms.add(regualrListForm);
            }
            commodityDetailRegualrForm.setRegualrs(regualrListForms);
            regualrCombo.add(commodityDetailRegualrForm);
        }
        commodityDetailVo.setRegualrCombo(regualrCombo);

        // 组装配件、服务
        List<CommodityDetailExtralForm> extral = new ArrayList<>();
        List<String> types = new ArrayList<>();
        types.add(GoodsSpecificationConstant.TYPE_CUSTOM);
        types.add(GoodsSpecificationConstant.TYPE_EXTEND);
        types.add(GoodsSpecificationConstant.TYPE_ONLINE);
        AgedmallGoodsSpecificationInfoExample goodsSpecificationInfoExample = new AgedmallGoodsSpecificationInfoExample();
        goodsSpecificationInfoExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goodsId)
                .andTypeIn(types);
        List<AgedmallGoodsSpecificationInfo> goodsSpecificationInfos = agedmallGoodsSpecificationInfoMapper.selectByExample(goodsSpecificationInfoExample);
        for (AgedmallGoodsSpecificationInfo goodsSpecificationInfo : goodsSpecificationInfos) {
            CommodityDetailExtralForm commodityDetailExtralForm = new CommodityDetailExtralForm();
            commodityDetailExtralForm.setSpecInfoId(goodsSpecificationInfo.getId());
            commodityDetailExtralForm.setName(goodsSpecificationInfo.getSpecName());
            commodityDetailExtralForm.setType(goodsSpecificationInfo.getType());
            commodityDetailExtralForm.setMustSelect(goodsSpecificationInfo.getMinSelCount() > 0 ? 1 : 0);
            commodityDetailExtralForm.setMultiSelFlg(goodsSpecificationInfo.getMultiSelFlg() ? 1 : 0);
            commodityDetailExtralForm.setDesc(goodsSpecificationInfo.getDesc());

            List<CommodityDetailExtralListForm> values = new ArrayList<>();
            LitemallGoodsSpecificationExample litemallGoodsSpecificationExample = new LitemallGoodsSpecificationExample();
            litemallGoodsSpecificationExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdEqualTo(goodsId)
                    .andParentIdEqualTo(goodsSpecificationInfo.getId());
            List<LitemallGoodsSpecification> specificationList = litemallGoodsSpecificationMapper.selectByExample(litemallGoodsSpecificationExample);
            for (LitemallGoodsSpecification litemallGoodsSpecification : specificationList) {
                LitemallGoodsProduct product = null;
                Integer relationId = null;
                Integer payOrder = null;
                // 普通服务
                if (GoodsSpecificationConstant.TYPE_EXTEND.equals(goodsSpecificationInfo.getType())) {
                    product = backendGoodsMapper.getServiceProductBySpecId(litemallGoodsSpecification.getId());
                // 配件
                } else if (GoodsSpecificationConstant.TYPE_CUSTOM.equals(goodsSpecificationInfo.getType())) {
                    AgedmallGoodsPartsExample partsExample = new AgedmallGoodsPartsExample();
                    partsExample.createCriteria().andDeletedEqualTo(false)
                            .andSpecIdEqualTo(litemallGoodsSpecification.getId());
                    AgedmallGoodsParts parts = agedmallGoodsPartsMapper.selectOneByExample(partsExample);
                    relationId = null == parts ? null : parts.getCustomizedGoodsId();
                    payOrder = null == parts ? null : parts.getPayOrder();
                // 在线服务
                } else if (GoodsSpecificationConstant.TYPE_ONLINE.equals(goodsSpecificationInfo.getType())) {
                    AgedmallGoodsOnlineServiceExample onlineServiceExample = new AgedmallGoodsOnlineServiceExample();
                    onlineServiceExample.createCriteria().andDeletedEqualTo(false)
                            .andSpecIdEqualTo(litemallGoodsSpecification.getId());
                    AgedmallGoodsOnlineService onlineService = agedmallGoodsOnlineServiceMapper.selectOneByExample(onlineServiceExample);
                    relationId = null == onlineService ? null : onlineService.getOnlineSerivceProductId();
                    payOrder = null == onlineService ? null : onlineService.getPayOrder();
                }


                CommodityDetailExtralListForm commodityDetailExtralListForm = new CommodityDetailExtralListForm();
//                commodityDetailExtralListForm.setProductId(product.getId());
                commodityDetailExtralListForm.setCommodityid(relationId);
                commodityDetailExtralListForm.setPayOrder(payOrder);
                commodityDetailExtralListForm.setValue(litemallGoodsSpecification.getValue());
                commodityDetailExtralListForm.setSpecId(litemallGoodsSpecification.getId());
//                    commodityDetailExtralListForm.setCost(product.getPrice());
//                    commodityDetailExtralListForm.setOrginalPrice(product.getOriginalPrice());
//                    commodityDetailExtralListForm.setWeight(product.getWeight());
                values.add(commodityDetailExtralListForm);

            }
            commodityDetailExtralForm.setValues(values);
            extral.add(commodityDetailExtralForm);
        }
        commodityDetailVo.setExtral(extral);

        return ResponseUtil.ok(commodityDetailVo);
    }

    @Transactional
    public Object delCommodity(List<Integer> idList) {
        if (CollectionUtils.isNotEmpty(idList)) {
            LitemallGoodsExample example = new LitemallGoodsExample();
            example.createCriteria().andDeletedEqualTo(false)
                    .andIdIn(idList);
            litemallGoodsMapper.logicalDeleteByExample(example);

            // 删除规格类型表
            AgedmallGoodsSpecificationInfoExample agedmallGoodsSpecificationInfoExample = new AgedmallGoodsSpecificationInfoExample();
            agedmallGoodsSpecificationInfoExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdIn(idList);
            agedmallGoodsSpecificationInfoMapper.logicalDeleteByExample(agedmallGoodsSpecificationInfoExample);
            // 删除规格表
            LitemallGoodsSpecificationExample litemallGoodsSpecificationExample = new LitemallGoodsSpecificationExample();
            litemallGoodsSpecificationExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdIn(idList);
            litemallGoodsSpecificationMapper.logicalDeleteByExample(litemallGoodsSpecificationExample);
            // 删除规格商品表
            LitemallGoodsProductExample litemallGoodsProductExample = new LitemallGoodsProductExample();
            litemallGoodsProductExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdIn(idList);
            litemallGoodsProductMapper.logicalDeleteByExample(litemallGoodsProductExample);
            // 删除配件表
            AgedmallGoodsPartsExample agedmallGoodsPartsExample = new AgedmallGoodsPartsExample();
            agedmallGoodsPartsExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdIn(idList);
            agedmallGoodsPartsMapper.logicalDeleteByExample(agedmallGoodsPartsExample);
            // 删除服务表
            AgedmallGoodsServiceExample agedmallGoodsServiceExample = new AgedmallGoodsServiceExample();
            agedmallGoodsServiceExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdIn(idList);
            agedmallGoodsServiceMapper.logicalDeleteByExample(agedmallGoodsServiceExample);
            // 删除在线服务表
            AgedmallGoodsOnlineServiceExample agedmallGoodsOnlineServiceExample = new AgedmallGoodsOnlineServiceExample();
            agedmallGoodsOnlineServiceExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdIn(idList);
            agedmallGoodsOnlineServiceMapper.logicalDeleteByExample(agedmallGoodsOnlineServiceExample);
            // 删除抵扣金配置
            AgedmallGoodsDeductionConfExample agedmallGoodsDeductionConfExample = new AgedmallGoodsDeductionConfExample();
            agedmallGoodsDeductionConfExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdIn(idList);
            agedmallGoodsDeductionConfMapper.logicalDeleteByExample(agedmallGoodsDeductionConfExample);

            //删除商品绑定的rfid设备
            AgedmallGoodsEquExample goodsEquExample =new AgedmallGoodsEquExample();
            List<Long> longIdList=new ArrayList<>();
            for (int i = 0; i < idList.size(); i++) {
                longIdList.add(idList.get(i).longValue());
            }
            goodsEquExample.or().andGoodsIdIn(longIdList).andDeletedEqualTo((byte)0);
            agedmallGoodsEquMapper.logicalDeleteByExample(goodsEquExample);
        }
        return ResponseUtil.ok();
    }

    public Object changeState(List<Integer> idList, Integer commodityState) {
        if (CollectionUtils.isNotEmpty(idList)) {
            LitemallGoodsExample example = new LitemallGoodsExample();
            example.createCriteria().andDeletedEqualTo(false)
                    .andIdIn(idList);
            LitemallGoods goods = new LitemallGoods();
            goods.setIsOnSale(commodityState == 1);
            litemallGoodsMapper.updateByExampleSelective(goods, example);
        }
        return ResponseUtil.ok();
    }

    public Object linkShopList(Integer busiId, Integer type, Integer commodityId, Integer province, Integer city, Integer area, String shopKeyWords,
                               Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<BackendLinkStoreListVo> list = backendStoreMapper.linkShopList(busiId, type, commodityId, province, city, area, shopKeyWords);
        list.stream().forEach(p -> {
            if (StringUtils.isNotEmpty(p.getWarehouseType())) {
                p.setWarehouseType(p.getWarehouseType().replaceFirst(",", ""));
            }
        });
        return ResponseUtil.okList(list);
    }

    @Transactional
    public Object linkShops(CommodityAddLinkShopForm commodityLinkShopsForm) {
        if (CollectionUtils.isNotEmpty(commodityLinkShopsForm.getShopIds())) {
            for (Integer shopId : commodityLinkShopsForm.getShopIds()) {
                commodityLinkShopsForm.setShopId(shopId);
                addLinkShop(commodityLinkShopsForm);
            }
        }
        return ResponseUtil.ok();
    }

    @Transactional
    public Object addLinkShop(CommodityAddLinkShopForm commodityAddLinkShopForm) {
        // 商品价格有规格取规格最低值
        BigDecimal retailPrice = commodityAddLinkShopForm.getRetailPrice();
        BigDecimal deposit = commodityAddLinkShopForm.getDeposit();
        if (CollectionUtils.isNotEmpty(commodityAddLinkShopForm.getProductList())) {
            retailPrice = commodityAddLinkShopForm.getProductList().stream().map(p -> null == p.getPrice() ? BigDecimal.ZERO : p.getPrice())
                    .min(Comparator.naturalOrder()).orElse(BigDecimal.ZERO);
            deposit = commodityAddLinkShopForm.getProductList().stream().map(p -> null == p.getDeposit() ? BigDecimal.ZERO : p.getDeposit())
                    .min(Comparator.naturalOrder()).orElse(BigDecimal.ZERO);
        }
        // 保存门店商品关系
        AgedmallStoreGoods storeGoods = new AgedmallStoreGoods();
        storeGoods.setStoreId(commodityAddLinkShopForm.getShopId().longValue());
        storeGoods.setGoodsId(commodityAddLinkShopForm.getCommodityId().longValue());
        storeGoods.setOnlyToHospital(commodityAddLinkShopForm.getOnlyToHospital());
        storeGoods.setGoodsStock(commodityAddLinkShopForm.getGoodsStock());
        storeGoods.setChainLock(commodityAddLinkShopForm.getChainLock());
        storeGoods.setCabinetLock(commodityAddLinkShopForm.getCabinetLock());
        storeGoods.setCloudLock(commodityAddLinkShopForm.getCloudLock());
        storeGoods.setFreight(commodityAddLinkShopForm.getFreeDeliveryType());
        storeGoods.setNoDepositStat(commodityAddLinkShopForm.getNoDepositStat());
        storeGoods.setCollectionPointsType(commodityAddLinkShopForm.getIsRecovery());
        //云仓
        storeGoods.setCloudId(commodityAddLinkShopForm.getCloudStoreList());
        //回收点
        Integer isRecovery = commodityAddLinkShopForm.getIsRecovery();
        if(isRecovery != null &&  isRecovery == 1){
            storeGoods.setCollectionPoints(commodityAddLinkShopForm.getRecoveryList());
            PickUpModelForm pickUpModelForm = commodityAddLinkShopForm.getRecoveryFee();
            if(pickUpModelForm != null) {
                storeGoods.setCollectionPriceType(pickUpModelForm.getRecoveryType());
                storeGoods.setCollectionJson(JSONArray.toJSONString(pickUpModelForm.getRecoveryList()));
            }
        }

        if (AgedmallStoreGoodsConstant.FREIGHT_CONDITION_FREE.equals(commodityAddLinkShopForm.getFreeDeliveryType())) {
            storeGoods.setFreightCondition(commodityAddLinkShopForm.getFreeDeliveryPrice());
        }
        storeGoods.setPickFreight(commodityAddLinkShopForm.getFreePickType());
        if (AgedmallStoreGoodsConstant.FREIGHT_CONDITION_FREE.equals(commodityAddLinkShopForm.getFreePickType())) {
            storeGoods.setPickFreightCondition(commodityAddLinkShopForm.getFreePickPrice());
        }
        storeGoods.setSaleRetailPrice(retailPrice);
        storeGoods.setDeposit(deposit);
        storeGoods.setLeaseChargeTemplateId(commodityAddLinkShopForm.getLeaseChargeTemplateId());
        storeGoods.setMaintainTemplateId(commodityAddLinkShopForm.getOperateId().longValue());
        storeGoods.setLogisticsType(commodityAddLinkShopForm.getLogisticsType().byteValue());
        storeGoods.setPayOrder(commodityAddLinkShopForm.getPayOrder());
        //统一运费
        if (AgedmallStoreGoodsConstant.LOGISTICS_TYPE_COST == commodityAddLinkShopForm.getLogisticsType().byteValue()) {
            ExpressModelForm flatFee = commodityAddLinkShopForm.getFlatFee();
            storeGoods.setPayOrder(flatFee.getPayOrder());
            storeGoods.setSameCitySendType(flatFee.getSameCityDelivery().getDelivery());
            //物流
            if(flatFee.getSameCityDelivery().getDelivery()==0){
                storeGoods.setSameCityLogisticsCompanyType(flatFee.getSameCityDelivery().getDeliveryExpressId());
                storeGoods.setExpressCost(flatFee.getSameCityDelivery().getDeliveryCost());

            }
            else{
                storeGoods.setSameCityCost(flatFee.getSameCityDelivery().getDeliveryCost());
            }


            //物流公司
            storeGoods.setSameCityLogisticsCompanyType(flatFee.getSameCityDelivery().getDeliveryExpressId());
            storeGoods.setPickUpLogisticsCompanyType(flatFee.getSameCityDelivery().getRecoveryExpressId());

            storeGoods.setSendFastestTime(flatFee.getSameCityDelivery().getSendFastestTime());
            storeGoods.setSendSlowestTime(flatFee.getSameCityDelivery().getSendSlowestTime());

            storeGoods.setPickUpType(flatFee.getSameCityDelivery().getRecovery());
            if(flatFee.getSameCityDelivery().getRecovery()!=null){
                //物流
                if(flatFee.getSameCityDelivery().getRecovery()==0){
                    storeGoods.setPickUpLogisticsCompanyType(flatFee.getSameCityDelivery().getRecovery());
                }
                storeGoods.setPickUpCost(flatFee.getSameCityDelivery().getRecoveryCost());
            }
            storeGoods.setCloudJson(JSONArray.toJSONString(flatFee.getCloudStoreExpressList()));
        }
        //运费模板
        else {
            ExpressModelForm flatFee = commodityAddLinkShopForm.getExpressModel();
            if(flatFee != null) {
                storeGoods.setPayOrder(flatFee.getPayOrder());
                storeGoods.setSameCitySendType(flatFee.getSameCityDelivery().getDelivery());
                //物流
                if (flatFee.getSameCityDelivery().getDelivery() == 0) {
                    storeGoods.setSameCityLogisticsCompanyType(flatFee.getSameCityDelivery().getDeliveryExpressId());
                    storeGoods.setExpress(flatFee.getSameCityDelivery().getDeliveryModelId().longValue());
                } else {
                    storeGoods.setSameCity(flatFee.getSameCityDelivery().getDeliveryModelId().longValue());
                }

                //物流公司
                storeGoods.setSameCityLogisticsCompanyType(flatFee.getSameCityDelivery().getDeliveryExpressId());
                storeGoods.setPickUpLogisticsCompanyType(flatFee.getSameCityDelivery().getRecoveryExpressId());

                storeGoods.setPickUpType(flatFee.getSameCityDelivery().getRecovery());
                if(flatFee.getSameCityDelivery().getRecovery()!=null){
                    //物流
                    if (flatFee.getSameCityDelivery().getRecovery() == 0) {
                        storeGoods.setPickUpLogisticsCompanyType(flatFee.getSameCityDelivery().getRecovery());
                    }
                    storeGoods.setPickUp(flatFee.getSameCityDelivery().getRecoveryModelId().longValue());
                }
                storeGoods.setCloudJson(JSONArray.toJSONString(flatFee.getCloudStoreExpressList()));
            }
        }

        if (null == commodityAddLinkShopForm.getStoreGoodsId()) {
            storeGoods.setAddTime(LocalDateTime.now());
            agedmallStoreGoodsMapper.insertSelective(storeGoods);
        } else {
            storeGoods.setId(commodityAddLinkShopForm.getStoreGoodsId());
            storeGoods.setUpdateTime(LocalDateTime.now());
            agedmallStoreGoodsMapper.updateByPrimaryKeySelective(storeGoods);
        }

        if (null != commodityAddLinkShopForm.getStoreGoodsId()) {
            // 删除原有规格商品
            AgedmallStoreGoodsProductExample agedmallStoreGoodsProductExample = new AgedmallStoreGoodsProductExample();
            agedmallStoreGoodsProductExample.createCriteria()
                    .andDeletedEqualTo(false)
                    .andStoreIdEqualTo(commodityAddLinkShopForm.getShopId().longValue())
                    .andStoreGoodsIdEqualTo(storeGoods.getId());
            agedmallStoreGoodsProductMapper.logicalDeleteByExample(agedmallStoreGoodsProductExample);
        }

        // 保存门店规格商品
        if (CollectionUtils.isNotEmpty(commodityAddLinkShopForm.getProductList())) {
            for (CommodityAddLinkShopProductForm commodityAddLinkShopProductForm : commodityAddLinkShopForm.getProductList()) {
                AgedmallStoreGoodsProduct agedmallStoreGoodsProduct = new AgedmallStoreGoodsProduct();
                agedmallStoreGoodsProduct.setStoreId(commodityAddLinkShopForm.getShopId().longValue());
                agedmallStoreGoodsProduct.setStoreGoodsId(storeGoods.getId());
                agedmallStoreGoodsProduct.setGoodsProductId(commodityAddLinkShopProductForm.getProductId().longValue());
                agedmallStoreGoodsProduct.setProductStock(commodityAddLinkShopProductForm.getStock());
                agedmallStoreGoodsProduct.setRetailPrice(commodityAddLinkShopProductForm.getPrice());
                agedmallStoreGoodsProduct.setDeposit(commodityAddLinkShopProductForm.getDeposit());
                agedmallStoreGoodsProduct.setAddTime(LocalDateTime.now());
                agedmallStoreGoodsProductMapper.insertSelective(agedmallStoreGoodsProduct);
            }
        }
        inventoryUtil.refresh(commodityAddLinkShopForm.getShopId(),0);
        return ResponseUtil.ok();
    }

    @Transactional
    public Object unlinkShop(Long commodityId, List<Long> shopIds) {
        for (Long shopId : shopIds) {
            AgedmallStoreGoodsExample agedmallStoreGoodsExample = new AgedmallStoreGoodsExample();
            agedmallStoreGoodsExample.createCriteria().andDeletedEqualTo(false)
                    .andStoreIdEqualTo(shopId)
                    .andGoodsIdEqualTo(commodityId);
            AgedmallStoreGoods agedmallStoreGoods = agedmallStoreGoodsMapper.selectOneByExample(agedmallStoreGoodsExample);
            if (null != agedmallStoreGoods) {
                agedmallStoreGoodsMapper.logicalDeleteByPrimaryKey(agedmallStoreGoods.getId());

                // 删除规格商品
                AgedmallStoreGoodsProductExample agedmallStoreGoodsProductExample = new AgedmallStoreGoodsProductExample();
                agedmallStoreGoodsProductExample.createCriteria()
                        .andDeletedEqualTo(false)
                        .andStoreIdEqualTo(shopId)
                        .andStoreGoodsIdEqualTo(agedmallStoreGoods.getId());
                agedmallStoreGoodsProductMapper.logicalDeleteByExample(agedmallStoreGoodsProductExample);
            }

            // 删除门店商品rfid
            backendGoodsMapper.updateStoreGoodsRfid(commodityId, shopId);

            inventoryUtil.refresh(shopId.intValue(),0);
        }
        return ResponseUtil.ok();
    }

    public Object storeDetail(Long commodityId, Long shopId) {
        AgedmallStoreGoodsExample storeGoodsExample = new AgedmallStoreGoodsExample();
        storeGoodsExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(commodityId)
                .andStoreIdEqualTo(shopId);
        AgedmallStoreGoods agedmallStoreGoods = agedmallStoreGoodsMapper.selectOneByExample(storeGoodsExample);
        if (null == agedmallStoreGoods) {
            return ResponseUtil.badArgumentValue();
        }
        return getStoreCommodityDetail(agedmallStoreGoods);
    }

    public Object storeCommodityDetail(Long storeGoodsId) {
        AgedmallStoreGoods agedmallStoreGoods = agedmallStoreGoodsMapper.selectByPrimaryKey(storeGoodsId);
        if (null == agedmallStoreGoods) {
            return ResponseUtil.badArgumentValue();
        }
        return getStoreCommodityDetail(agedmallStoreGoods);
    }

    private Object getStoreCommodityDetail(AgedmallStoreGoods agedmallStoreGoods) {
        StoreCommodityDetailVo storeCommodityDetailVo = new StoreCommodityDetailVo();
        storeCommodityDetailVo.setStoreGoodsId(agedmallStoreGoods.getId().intValue());
        // 组装门店、商品
        AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(agedmallStoreGoods.getStoreId());
        if (null != store) {
            storeCommodityDetailVo.setShopId(store.getId().intValue());
            storeCommodityDetailVo.setShopName(store.getStoreName());
            storeCommodityDetailVo.setShopPic(store.getLogo());
            storeCommodityDetailVo.setShopAddress(store.getAddressDetail());
        }
        Integer goodsId = agedmallStoreGoods.getGoodsId().intValue();
        LitemallGoods goods = litemallGoodsMapper.selectByPrimaryKey(goodsId);
        if (null != goods) {
            storeCommodityDetailVo.setCommodityId(goods.getId());
            storeCommodityDetailVo.setCommodityName(goods.getName());
            storeCommodityDetailVo.setCommodityPic(goods.getPicUrl());
            storeCommodityDetailVo.setCommodityType(goods.getGoodsType());
        }

        storeCommodityDetailVo.setOnlyToHospital(agedmallStoreGoods.getOnlyToHospital());
        storeCommodityDetailVo.setGoodsStock(agedmallStoreGoods.getGoodsStock());
        storeCommodityDetailVo.setChainLock(agedmallStoreGoods.getChainLock());
        storeCommodityDetailVo.setChainLockNumber(null);
        storeCommodityDetailVo.setCabinetLock(agedmallStoreGoods.getCabinetLock());
        storeCommodityDetailVo.setCabinetLockNumber(null);
        storeCommodityDetailVo.setCloudLock(agedmallStoreGoods.getCloudLock());
        storeCommodityDetailVo.setCloudLockNumber(null);
        storeCommodityDetailVo.setFreeDeliveryType(agedmallStoreGoods.getFreight());
        storeCommodityDetailVo.setFreeDeliveryPrice(agedmallStoreGoods.getFreightCondition());
        storeCommodityDetailVo.setFreePickType(agedmallStoreGoods.getPickFreight());
        storeCommodityDetailVo.setFreePickPrice(agedmallStoreGoods.getPickFreightCondition());
        storeCommodityDetailVo.setRetailPrice(agedmallStoreGoods.getSaleRetailPrice());
        storeCommodityDetailVo.setLeaseChargeTemplateId(agedmallStoreGoods.getLeaseChargeTemplateId());
        storeCommodityDetailVo.setOperateId(agedmallStoreGoods.getMaintainTemplateId());
        storeCommodityDetailVo.setLogisticsType(agedmallStoreGoods.getLogisticsType());
        storeCommodityDetailVo.setPayOrder(agedmallStoreGoods.getPayOrder());
        storeCommodityDetailVo.setExpress(agedmallStoreGoods.getExpress());
        storeCommodityDetailVo.setSameCity(agedmallStoreGoods.getSameCity());
        storeCommodityDetailVo.setExpressCost(agedmallStoreGoods.getExpressCost());
        storeCommodityDetailVo.setSameCityCost(agedmallStoreGoods.getSameCityCost());
        storeCommodityDetailVo.setSendFastestTime(agedmallStoreGoods.getSendFastestTime());
        storeCommodityDetailVo.setSendSlowestTime(agedmallStoreGoods.getSendSlowestTime());
        storeCommodityDetailVo.setNoDepositStat(agedmallStoreGoods.getNoDepositStat());

        storeCommodityDetailVo.setSameCitySendType(agedmallStoreGoods.getSameCitySendType());
        storeCommodityDetailVo.setPickUpType(agedmallStoreGoods.getPickUpType());
        storeCommodityDetailVo.setSameCityLogisticsCompanyType(agedmallStoreGoods.getSameCityLogisticsCompanyType());
        storeCommodityDetailVo.setPickUpLogisticsCompanyType(agedmallStoreGoods.getPickUpLogisticsCompanyType());
        storeCommodityDetailVo.setPickUp(agedmallStoreGoods.getPickUp());
        storeCommodityDetailVo.setPickUpCost(agedmallStoreGoods.getPickUpCost());
        storeCommodityDetailVo.setCloudJson(agedmallStoreGoods.getCloudJson());
        storeCommodityDetailVo.setCollectionPointsType(agedmallStoreGoods.getCollectionPointsType());
        if(StringUtils.isNotBlank(agedmallStoreGoods.getCollectionPoints())){
            List<Integer> idList=new ArrayList<>();
            String[] arrayIds=agedmallStoreGoods.getCollectionPoints().split(",");
            Arrays.stream(arrayIds).forEach( id ->idList.add(Integer.parseInt(id)));
            AgedmallCollectionPointsExample collectionPointsExample=new AgedmallCollectionPointsExample();
            collectionPointsExample.createCriteria().andDeletedEqualTo(false).andIdIn(idList);
            List<AgedmallCollectionPoints> agedmallCollectionPoints = agedmallCollectionPointsMapper.selectByExample(collectionPointsExample);
            storeCommodityDetailVo.setCollectionPoints(agedmallCollectionPoints);
        }
        storeCommodityDetailVo.setCollectionPriceType(agedmallStoreGoods.getCollectionPriceType());
        storeCommodityDetailVo.setCollectionJson(agedmallStoreGoods.getCollectionJson());
        if(StringUtils.isNotBlank(agedmallStoreGoods.getCloudId())){
            List<Integer> idList=new ArrayList<>();
            String[] arrayIds=agedmallStoreGoods.getCloudId().split(",");
            Arrays.stream(arrayIds).forEach( id ->idList.add(Integer.parseInt(id)));
            AgedmallCloudHouseExample cloudHouseExample=new AgedmallCloudHouseExample();
            cloudHouseExample.createCriteria().andDeletedEqualTo(false).andIdIn(idList);
            List<AgedmallCloudHouse> agedmallCloudHouses = agedmallCloudHouseMapper.selectByExample(cloudHouseExample);
            storeCommodityDetailVo.setCloudList(agedmallCloudHouses);
        }


        // 组装常规规格
        List<CommodityDetailRegualrNameForm> regualrList = new ArrayList<>();
        AgedmallGoodsSpecificationInfoExample agedmallGoodsSpecificationInfoExample = new AgedmallGoodsSpecificationInfoExample();
        agedmallGoodsSpecificationInfoExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goodsId)
                .andTypeEqualTo(GoodsSpecificationConstant.TYPE_SPEC);
        List<AgedmallGoodsSpecificationInfo> goodsSpecificationInfoList = agedmallGoodsSpecificationInfoMapper.selectByExample(agedmallGoodsSpecificationInfoExample);
        for (AgedmallGoodsSpecificationInfo specificationInfo : goodsSpecificationInfoList) {
            CommodityDetailRegualrNameForm commodityDetailRegualrNameForm = new CommodityDetailRegualrNameForm();
            commodityDetailRegualrNameForm.setSpecInfoId(specificationInfo.getId());
            commodityDetailRegualrNameForm.setName(specificationInfo.getSpecName());

            List<CommodityDetailRegualrValueForm> valueList = new ArrayList<>();
            LitemallGoodsSpecificationExample litemallGoodsSpecificationExample = new LitemallGoodsSpecificationExample();
            litemallGoodsSpecificationExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdEqualTo(goodsId)
                    .andParentIdEqualTo(specificationInfo.getId());
            List<LitemallGoodsSpecification> specificationList = litemallGoodsSpecificationMapper.selectByExample(litemallGoodsSpecificationExample);
            for (LitemallGoodsSpecification litemallGoodsSpecification : specificationList) {
                CommodityDetailRegualrValueForm commodityDetailRegualrValueForm = new CommodityDetailRegualrValueForm();
                commodityDetailRegualrValueForm.setSpecId(litemallGoodsSpecification.getId());
                commodityDetailRegualrValueForm.setValue(litemallGoodsSpecification.getValue());
                valueList.add(commodityDetailRegualrValueForm);
            }
            commodityDetailRegualrNameForm.setValueList(valueList);
            regualrList.add(commodityDetailRegualrNameForm);
        }
        storeCommodityDetailVo.setRegualrList(regualrList);

        List<CommodityDetailRegualrForm> regualrCombo = new ArrayList<>();
        LitemallGoodsProductExample litemallGoodsProductExample = new LitemallGoodsProductExample();
        litemallGoodsProductExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goodsId)
                .andTypeEqualTo(GoodsProductConstant.TYPE_GOODS);
        List<LitemallGoodsProduct> litemallGoodsProductList = litemallGoodsProductMapper.selectByExample(litemallGoodsProductExample);
        // 组装常规规格商品
        for (LitemallGoodsProduct product : litemallGoodsProductList) {
            AgedmallStoreGoodsProductExample agedmallStoreGoodsProductExample = new AgedmallStoreGoodsProductExample();
            agedmallStoreGoodsProductExample.createCriteria()
                    .andDeletedEqualTo(false)
                    .andGoodsProductIdEqualTo(product.getId().longValue())
                    .andStoreGoodsIdEqualTo(agedmallStoreGoods.getId());
            AgedmallStoreGoodsProduct storeGoodsProduct = agedmallStoreGoodsProductMapper.selectOneByExample(agedmallStoreGoodsProductExample);
            CommodityDetailRegualrForm commodityDetailRegualrForm = new CommodityDetailRegualrForm();
            commodityDetailRegualrForm.setProductId(product.getId());
            commodityDetailRegualrForm.setCost(storeGoodsProduct.getRetailPrice());
            commodityDetailRegualrForm.setDeposit(storeGoodsProduct.getDeposit());
            commodityDetailRegualrForm.setCloudStock(storeGoodsProduct.getProductStock());

            List<CommodityDetailRegualrListForm> regualrListForms = new ArrayList<>();
            List<LitemallGoodsProductSpecification> specList = JSON.parseArray(product.getSpecifications(), LitemallGoodsProductSpecification.class);
            for (LitemallGoodsProductSpecification specification : specList) {
                CommodityDetailRegualrListForm regualrListForm = new CommodityDetailRegualrListForm();
                regualrListForm.setSpecId(specification.getId());
                regualrListForm.setName(specification.getInfoName());
                regualrListForm.setValue(specification.getName());
                regualrListForms.add(regualrListForm);
            }
            commodityDetailRegualrForm.setRegualrs(regualrListForms);
            regualrCombo.add(commodityDetailRegualrForm);
        }
        storeCommodityDetailVo.setRegualrCombo(regualrCombo);

        // 组装配件、服务
        List<CommodityDetailExtralForm> extral = new ArrayList<>();
        List<String> types = new ArrayList<>();
        types.add(GoodsSpecificationConstant.TYPE_CUSTOM);
        types.add(GoodsSpecificationConstant.TYPE_EXTEND);
        types.add(GoodsSpecificationConstant.TYPE_ONLINE);
        AgedmallGoodsSpecificationInfoExample goodsSpecificationInfoExample = new AgedmallGoodsSpecificationInfoExample();
        goodsSpecificationInfoExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goodsId)
                .andTypeIn(types);
        List<AgedmallGoodsSpecificationInfo> goodsSpecificationInfos = agedmallGoodsSpecificationInfoMapper.selectByExample(goodsSpecificationInfoExample);
        for (AgedmallGoodsSpecificationInfo goodsSpecificationInfo : goodsSpecificationInfos) {
            CommodityDetailExtralForm commodityDetailExtralForm = new CommodityDetailExtralForm();
            commodityDetailExtralForm.setSpecInfoId(goodsSpecificationInfo.getId());
            commodityDetailExtralForm.setName(goodsSpecificationInfo.getSpecName());
            commodityDetailExtralForm.setType(goodsSpecificationInfo.getType());
            commodityDetailExtralForm.setMustSelect(goodsSpecificationInfo.getMinSelCount() > 0 ? 1 : 0);
            commodityDetailExtralForm.setMultiSelFlg(goodsSpecificationInfo.getMultiSelFlg() ? 1 : 0);
            commodityDetailExtralForm.setDesc(goodsSpecificationInfo.getDesc());

            List<CommodityDetailExtralListForm> values = new ArrayList<>();
            LitemallGoodsSpecificationExample litemallGoodsSpecificationExample = new LitemallGoodsSpecificationExample();
            litemallGoodsSpecificationExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdEqualTo(goodsId)
                    .andParentIdEqualTo(goodsSpecificationInfo.getId());
            List<LitemallGoodsSpecification> specificationList = litemallGoodsSpecificationMapper.selectByExample(litemallGoodsSpecificationExample);
            for (LitemallGoodsSpecification litemallGoodsSpecification : specificationList) {
                LitemallGoodsProduct product = null;
                Integer relationId = null;
                // 普通服务
                if (GoodsSpecificationConstant.TYPE_EXTEND.equals(goodsSpecificationInfo.getType())) {
                    product = backendGoodsMapper.getServiceProductBySpecId(litemallGoodsSpecification.getId());
                // 配件
                } else if (GoodsSpecificationConstant.TYPE_CUSTOM.equals(goodsSpecificationInfo.getType())){
                    AgedmallGoodsPartsExample partsExample = new AgedmallGoodsPartsExample();
                    partsExample.createCriteria().andDeletedEqualTo(false)
                            .andSpecIdEqualTo(litemallGoodsSpecification.getId());
                    AgedmallGoodsParts parts = agedmallGoodsPartsMapper.selectOneByExample(partsExample);
                    relationId = null == parts ? null : parts.getCustomizedGoodsId();
                // 在线服务
                } else if (GoodsSpecificationConstant.TYPE_ONLINE.equals(goodsSpecificationInfo.getType())) {
                    AgedmallGoodsOnlineServiceExample onlineServiceExample = new AgedmallGoodsOnlineServiceExample();
                    onlineServiceExample.createCriteria().andDeletedEqualTo(false)
                            .andSpecIdEqualTo(litemallGoodsSpecification.getId());
                    AgedmallGoodsOnlineService onlineService = agedmallGoodsOnlineServiceMapper.selectOneByExample(onlineServiceExample);
                    relationId = null == onlineService ? null : onlineService.getOnlineSerivceProductId();
                }

//                AgedmallStoreGoodsProductExample storeGoodsProductExample = new AgedmallStoreGoodsProductExample();
//                storeGoodsProductExample.createCriteria().andGoodsProductIdEqualTo(product.getId().longValue())
//                        .andStoreGoodsIdEqualTo(agedmallStoreGoods.getId());
//                AgedmallStoreGoodsProduct storeGoodsProduct = agedmallStoreGoodsProductMapper.selectOneByExample(storeGoodsProductExample);
                CommodityDetailExtralListForm commodityDetailExtralListForm = new CommodityDetailExtralListForm();
//                commodityDetailExtralListForm.setProductId(product.getId());
                commodityDetailExtralListForm.setValue(litemallGoodsSpecification.getValue());
//                commodityDetailExtralListForm.setStock(storeGoodsProduct.getProductStock());
                commodityDetailExtralListForm.setCommodityid(relationId);
//                    commodityDetailExtralListForm.setCost(storeGoodsProduct.getRetailPrice());
                values.add(commodityDetailExtralListForm);
            }
            commodityDetailExtralForm.setValues(values);
            extral.add(commodityDetailExtralForm);
        }
        storeCommodityDetailVo.setExtral(extral);

        return ResponseUtil.ok(storeCommodityDetailVo);
    }

    public Object setRentDescription(Integer busiId, CommodityDescForm commodityDescForm) {
        AgedmallExplainExample agedmallExplainExample = new AgedmallExplainExample();
        agedmallExplainExample.createCriteria()
                .andBusIdEqualTo(busiId.longValue())
                .andTypeEqualTo(commodityDescForm.getType());
        AgedmallExplain agedmallExplain = agedmallExplainMapper.selectOneByExampleWithBLOBs(agedmallExplainExample);
        if (null == agedmallExplain) {
            agedmallExplain = new AgedmallExplain();
        }
        agedmallExplain.setBusId(busiId.longValue());
        agedmallExplain.setType(commodityDescForm.getType());
        agedmallExplain.setContent(commodityDescForm.getContent());
        agedmallExplain.setProblemContent(commodityDescForm.getProblemContent());
        agedmallExplain.setFreightContent(commodityDescForm.getFreightContent());
        agedmallExplain.setDistributionModeContent(commodityDescForm.getDistributionModeContent());
        agedmallExplain.setLeaseTimeContent(commodityDescForm.getLeaseTimeContent());
        agedmallExplain.setFreightContentShort(commodityDescForm.getFreightContentShort());
        agedmallExplain.setDistributionModeContentShort(commodityDescForm.getDistributionModeContentShort());
        agedmallExplain.setLeaseTimeContentShort(commodityDescForm.getLeaseTimeContentShort());
        agedmallExplain.setPlaceOrderContent(commodityDescForm.getPlaceOrderContent()!=null?JSON.toJSONString(commodityDescForm.getPlaceOrderContent()):null);
        agedmallExplain.setAfterThatContent(commodityDescForm.getAfterThatContent());

        if (null == agedmallExplain.getId()) {
            agedmallExplainMapper.insert(agedmallExplain);
        } else {
            agedmallExplainMapper.updateByPrimaryKey(agedmallExplain);
        }

        return ResponseUtil.ok();
    }

    public Object getRentDescription(Integer busiId, @RequestParam Integer type) {
        AgedmallExplainExample agedmallExplainExample = new AgedmallExplainExample();
        agedmallExplainExample.createCriteria()
                .andBusIdEqualTo(busiId.longValue())
                .andTypeEqualTo(type);
        AgedmallExplain agedmallExplain = agedmallExplainMapper.selectOneByExampleWithBLOBs(agedmallExplainExample);
        if(ObjectUtil.isNull(agedmallExplain)){
            agedmallExplain=new AgedmallExplain();
            agedmallExplain.setType(type);
            agedmallExplain.setBusId(busiId.longValue());
            agedmallExplain.setContent("");
            agedmallExplain.setProblemContent("");
            agedmallExplain.setFreightContent("");
            agedmallExplain.setDistributionModeContent("");
            agedmallExplain.setLeaseTimeContent("");
            agedmallExplain.setFreightContentShort("");
            agedmallExplain.setDistributionModeContentShort("");
            agedmallExplain.setLeaseTimeContentShort("");
            agedmallExplain.setPlaceOrderContent("");
            agedmallExplain.setAfterThatContent("");
        }
        return ResponseUtil.ok(agedmallExplain);
    }

    public Object storeGoodsStock(Long commodityId, Long storeId) {
        Map map = new HashMap();
        map.put("chainLockNum", inventoryUtil.get(storeId.intValue(), InventoryUtil.TYPE_STORE, InventoryUtil.STOCK_SOFTCHAIN, commodityId.intValue(), null));
        map.put("cabinetLockNum", inventoryUtil.get(storeId.intValue(), InventoryUtil.TYPE_STORE, InventoryUtil.STOCK_CABINET, commodityId.intValue(), null));
        return ResponseUtil.ok(map);
    }

    public Object goodsCloudStock(Long commodityId) {
        Map map = new HashMap();
        int totalNum = 0;
        List<Integer> cloudIds = agedmallCloudHouseService.getIdsByGoodsId(commodityId.intValue());
        for (Integer cloudId : cloudIds) {
            int num = inventoryUtil.get(cloudId, InventoryUtil.TYPE_CLOUD, InventoryUtil.STOCK_CLOUD, commodityId.intValue(), null);
            totalNum += num;
        }
        map.put("cloudLockNum", totalNum);
        return ResponseUtil.ok(map);
    }
}
